using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Excel;
using Admin.NET.Application.Service.Report.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service.Report;

public class IncomeReportService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<PowerConsumptionRecord> _rep;

	private readonly SqlSugarRepository<ElectricMeter> _repQuery;

	public IncomeReportService(SqlSugarRepository<PowerConsumptionRecord> rep, SqlSugarRepository<ElectricMeter> repQuery)
	{
		_rep = rep;
		_repQuery = repQuery;
	}

	[HttpPost("/report/getincomeexecl")]
	public async Task<IActionResult> ExportIncome([FromBody] EneryInput input)
	{
		List<IncomeReport> list = await GetIncome(input);
		string str = "收入环比-" + DateTime.Now.ToString("yyyy-MM-dd");
		List<string> column = new List<string>();
		List<string> title = new List<string>();
		string titleEx = "收入环比";
		string now;
		string lasts;
		if (input.Type == 0)
		{
			now = "当日";
			lasts = "昨日";
			titleEx += input.Time.ToString("yyyy-MM-dd");
		}
		else
		{
			now = "当月";
			lasts = "上月";
			titleEx += input.Time.ToString("yyyy-MM");
		}
		column.AddRange(new string[6] { "MeterNo", "MeterName", "NowFee", "LastFee", "AddFee", "Specific" });
		title.AddRange(new string[6]
		{
			"表号",
			"名称",
			now + "收入（元）",
			lasts + "收入（元）",
			"增加收入（元）",
			"收入环比（%）"
		});
		MemoryStream memery = ExportToExcel.ExportToList(list.ToArray(), titleEx, titleEx, column.ToArray(), title.ToArray());
		byte[] aa = memery.ToArray();
		return new FileStreamResult(new MemoryStream(aa), "application/octet-stream")
		{
			FileDownloadName = str + ".xlsx"
		};
	}

	[HttpPost("/report/getincome")]
	public async Task<List<IncomeReport>> GetIncome([FromBody] EneryInput input)
	{
		new List<IncomeReport>();
		List<MeterAllValue> lastValue = new List<MeterAllValue>();
		List<MeterAllValue> nowValue = new List<MeterAllValue>();
		new List<PowerMeter>();
		List<MeterInfo> meterAllInfo = await (from u in _repQuery.Context.Queryable<ElectricMeter>()
			where input.Ids.Contains(u.Id) && u.IsDelete == false
			select new MeterInfo
			{
				MeterNo = u.Sn,
				Id = u.Id,
				Name = u.Name
			}).ToListAsync();
		if (input.Type == 0)
		{
			DateTime starttime = input.Time.Date.AddDays(-1.0);
			DateTime endtime = input.Time.Date.AddDays(1.0);
			List<PowerMeter> result = await (from u in _rep.Context.Queryable<PowerConsumptionRecord>()
				where input.Ids.Contains(u.MeterId) && u.CreateTime >= starttime && u.CreateTime < endtime
				select new PowerMeter
				{
					CreateTime = u.CreateTime,
					MeterId = u.MeterId,
					Name = u.Name,
					Amount = u.Amount
				}).ToListAsync();
			nowValue = (from u in result
				where u.CreateTime >= input.Time.Date
				group u by new { u.MeterId } into u
				select new MeterAllValue
				{
					Id = u.Key.MeterId,
					AllCount = u.Sum((PowerMeter u) => u.Amount.Value)
				}).ToList();
			if (input.Time.Date == DateTime.Now.Date)
			{
				DateTime lastTimeNow = DateTime.Now.AddDays(-1.0);
				lastValue = (from u in result
					where u.CreateTime <= lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.Amount.Value)
					}).ToList();
			}
			else
			{
				DateTime lastTimeNow = DateTime.Now.Date;
				lastValue = (from u in result
					where u.CreateTime <= lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.Amount.Value)
					}).ToList();
			}
		}
		else
		{
			DateTime timeNow = new DateTime(input.Time.Year, input.Time.Month, 1);
			DateTime starttime = timeNow.AddMonths(-1);
			DateTime endtime = timeNow.AddMonths(1);
			List<PowerMeter> result = await (from u in _rep.Context.Queryable<PowerConsumptionRecord>()
				where input.Ids.Contains(u.MeterId) && u.CreateTime >= starttime && u.CreateTime < endtime
				select new PowerMeter
				{
					CreateTime = u.CreateTime,
					MeterId = u.MeterId,
					Name = u.Name,
					Amount = u.Amount
				}).ToListAsync();
			nowValue = (from u in result
				where u.CreateTime >= timeNow
				group u by new { u.MeterId } into u
				select new MeterAllValue
				{
					Id = u.Key.MeterId,
					AllCount = u.Sum((PowerMeter u) => u.Amount.Value)
				}).ToList();
			if (input.Time.Year == DateTime.Now.Year && input.Time.Month == DateTime.Now.Month)
			{
				DateTime lastTimeNow = DateTime.Now.Date.AddMonths(-1);
				lastValue = (from u in result
					where u.CreateTime <= lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.Amount.Value)
					}).ToList();
			}
			else
			{
				DateTime lastTimeNow = timeNow;
				lastValue = (from u in result
					where u.CreateTime < lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.Amount.Value)
					}).ToList();
			}
		}
		List<IncomeReport> list = meterAllInfo.Select((MeterInfo u) => new IncomeReport
		{
			MeterName = (from s in meterAllInfo
				where s.Id == u.Id
				select s.Name).FirstOrDefault(),
			NowFee = ((from s in nowValue
				where s.Id == u.Id
				select s into u
				select u.AllCount).FirstOrDefault().ToString() ?? ""),
			LastFee = ((from s in lastValue
				where s.Id == u.Id
				select s into u
				select u.AllCount).FirstOrDefault().ToString() ?? ""),
			MeterNo = (from s in meterAllInfo
				where s.Id == u.Id
				select s.MeterNo).FirstOrDefault()
		}).ToList();
		return list.OrderByDescending((IncomeReport u) => u.NowFee).ToList();
	}
}
